<template>
    <div class="catalog">
        <pageContainer ref="container" @current-page="handleCurrent" :total="total">
            <template #button>
                <el-button type="primary" plain @click="add" class="btn">新增</el-button>
                <el-button type="danger" plain @click="delBatch()" class="btn">批量删除</el-button>
            </template>
            <template #table>
                <el-table
                  ref="multipleTableRef"
                  :data="tableData"
                  row-key="id"
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column type="selection" :selectable="selectable" width="55" />
                  <el-table-column prop="categoryName" label="球场类型" width="130" />
                  <el-table-column prop="categoryIcon" label="球场图标" width="530" >
                    <template #default="scope">
                         <div style="width: 40px; height: 40px; border-radius: 4px; overflow: hidden; flex-shrink: 0;" @click="previewImg(scope.row)">
                            <el-image :src="scope.row.categoryIcon" fit="cover" style="width: 100%; height: 100%;" />
                         </div>
                    </template>
                  </el-table-column>
                  <el-table-column  label="操作" width="100">
                        <template #default="scope">
                            <el-button type="primary" :icon="Edit" circle plain @click="edit(scope.row,scope.$index)"></el-button>
                            <el-button type="danger" :icon="Delete" circle plain @click="del(scope.row,scope.$index)"></el-button>
                        </template>
                  </el-table-column>
                </el-table>
            </template>
        </pageContainer>

        <el-image-viewer 
          v-if="showViewer" 
          :url-list="previewImgs" 
          :initial-index="initialIndex" 
          @close="showViewer = false"
        />


        <!-- 新增或修改 -->
        <el-dialog v-model="dialogFormVisible" :title="title" width="400" :lock-scroll="false">
            <el-form :model="categoryModel">
              <el-form-item label="球场类型" :label-width="formLabelWidth">
                <el-input v-model="categoryModel.name" autocomplete="off" />
              </el-form-item>
              <el-form-item label="球场图标" :label-width="formLabelWidth">
                <el-upload
                    ref="uploadRef"
                    class="avatar-uploader"
                    :show-file-list="false"
                    :auto-upload="false"
                    :on-change="handleUpload"
                >
                    <img v-if="categoryModel.iconUrl" :src="categoryModel.iconUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="confirm">
                  确定
                </el-button>
              </div>
            </template>
          </el-dialog>

          
    </div>
</template>

<script setup>
import pageContainer from '@/components/page-container/page-container.vue';
import { onMounted, ref, watch } from 'vue';
import {
  Edit,Delete,Warning,Plus
} from '@element-plus/icons-vue'
import { commit, getCatalog } from '@/api/category';

const uploadRef=ref()
const tableData=ref([])
const dialogFormVisible=ref(false)
const title=ref('')
const container=ref()
const total=ref(0)
const categoryModel=ref({
  name:'',
  iconFile:'',  //传给后端
  iconUrl:''   //前端显示
})
const params=ref({
  current:1,
  pageSize:4
})

// 获取分类数据
const getData=async ()=>{
    const res=await getCatalog(params.value)
    console.log(res)
    // 给分页条的总数
    total.value=res.data.data.total
    tableData.value=res.data.data.records
} 

getData()

// 从子组件拿到当前页码
const handleCurrent=(e)=>{
   console.log(e)
   params.value.current=e
}

// 当前页码改变，重新请求数据
watch(()=>params.value.current,()=>{
  getData()
})

// 新增分类
const add=()=>{
   title.value='新增'
   categoryModel.value.name=''
   categoryModel.value.iconUrl=''
   dialogFormVisible.value=true
}

// 编辑分类
const edit=(row,index)=>{
   title.value='编辑'
   categoryModel.value.name=row.categoryName
   categoryModel.value.iconUrl=row.categoryIcon
   dialogFormVisible.value=true
}

const del=async (row,index)=>{
    container.value.open()
    // const res=await toDelete(row.categoryId)
    // console.log(res)
}

// 上传图片
const handleUpload=(file)=>{
    categoryModel.value.iconFile=file.raw

    // el-upload 组件选中图片后，需要手动将本地文件转为可预览的格式（如 Base64）
    const reader = new FileReader();
    reader.readAsDataURL(file.raw); // 转换为 Base64
    reader.onload = () => {
        categoryModel.value.iconUrl = reader.result; // 得到 Base64 字符串
    };
}

const confirm=async ()=>{
    const form=new FormData()
    form.append('name',categoryModel.value.name)
    form.append('icon',categoryModel.value.iconFile)

    await commit(form)
    dialogFormVisible.value=false

    getData()

}

const showViewer = ref(false); // 是否显示预览器
const previewImgs = ref([]); // 预览的图片数组

// 预览图片：接收图片数组和当前点击的索引
const previewImg = (row) => {
  const imageUrl=`http://localhost:8086${row.categoryIcon}`;
  previewImgs.value.push(imageUrl);
  showViewer.value = true;
};
</script>

<style lang='scss' scoped>
.catalog{
    .btn{
        height: 24px;
        font-size: 13px;
    }
    .avatar-uploader {
      :deep() {
        .avatar {
          width: 120px;
          height: 120px;
          display: block;
        }
        .el-upload {
          border: 1px dashed var(--el-border-color);
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          transition: var(--el-transition-duration-fast);
        }
        .el-upload:hover {
          border-color: var(--el-color-primary);
        }
        .el-icon.avatar-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          width: 120px;
          height: 120px;
          text-align: center;
        }
      }
    }
}
</style>